package com.huaxin.hxmoduleworkorder.controller;

import com.huaxin.hxmoduleworkorder.dto.ResponseCode;
import com.huaxin.hxmoduleworkorder.dto.ResponseResult;
import com.huaxin.hxmoduleworkorder.models.ScheduledTaskConfig;
import com.huaxin.hxmoduleworkorder.taskscheduler.DynamicTaskScheduler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "任务管理（巡查任务）")
@RestController
@RequiredArgsConstructor
@RequestMapping("/v1/workorder/taskManagement")
public class TaskManagementController {
    private final DynamicTaskScheduler dynamicTaskScheduler;

    /**
     * 查询所有支持的任务及其状态
     */
    @GetMapping("/getAllTasks")
    @Operation(summary = "查询所有支持的任务及其状态", description = "查询所有支持的任务及其状态")
    public ResponseResult<List<ScheduledTaskConfig>> getAllTasks() {
        return ResponseResult.ok(dynamicTaskScheduler.getAllTasks());
    }

    /**
     * 查询正在运行的任务
     */
    @GetMapping("/running")
    @Operation(summary = "查询正在运行的任务", description = "查询正在运行的任务")
    public ResponseResult<List<String>> getRunningTasks() {
        return ResponseResult.ok(dynamicTaskScheduler.getRunningTasks());
    }

    /**
     * 开启任务
     */
    @PostMapping("/start")
    @Operation(summary = "开启任务", description = "开启任务")
    public ResponseResult<String> startTask(@RequestParam String taskName) {
        try {
            dynamicTaskScheduler.startTask(taskName);
            return ResponseResult.ok("任务已启动: " + taskName);
        } catch (Exception e) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "启动失败: " + e.getMessage(), null);
        }
    }

    /**
     * 停止任务
     */
    @PostMapping("/stop")
    @Operation(summary = "停止任务", description = "停止任务")
    public ResponseResult<String> stopTask(@RequestParam String taskName) {
        dynamicTaskScheduler.stopTask(taskName);
        return ResponseResult.ok("任务已停止: " + taskName);
    }

}
